package com.jzo2o.customer.controller.operation;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.JwtTool;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 新增地址
 * @author L
 */
@Slf4j
@RestController
@RequestMapping("/consumer/address-book")
public class AddressBookController {

    @Resource
    private JwtTool jwtTool;

    @Resource
    private IAddressBookService addressBookService;


    @PostMapping
    public void insert(@RequestBody AddressBookUpsertReqDTO dto, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        addressBookService.insert(dto,token);
    }

    @GetMapping("/page")
    public PageResult<AddressBook> page(AddressBookPageQueryReqDTO dto, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        return addressBookService.page(dto,token);
    }

    @GetMapping("/{id}")
    public AddressBook selectOne(@PathVariable Long id){
        return addressBookService.getById(id);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable Long id,@RequestBody AddressBookUpsertReqDTO dto,HttpServletRequest request){
        if (Objects.isNull(id)){
            return;
        }
        String token = request.getHeader("Authorization");
        CurrentUserInfo currentUserInfo = jwtTool.parseToken(token);
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(dto,addressBook);
        //判断当前地址是否设置了默认地址
        if (dto.getIsDefault() == CertificationStatusEnum.PROGRESSING.getStatus()) {
            //被以前的默认地址修改为普通地址
            addressBookService.update(new AddressBook().setIsDefault(CertificationStatusEnum.INIT.getStatus())
                    , new LambdaQueryWrapper<AddressBook>()
                            .eq(AddressBook::getUserId, currentUserInfo.getId())
                            .eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING.getStatus()));
        }
        addressBookService.update(addressBook,new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getId,id));
    }

    @DeleteMapping("/batch")
    public void delete(@RequestBody List<Long> id){
        if (Objects.isNull(id)){
            return;
        }
        addressBookService.removeByIds(id);
    }

}
